<?php

namespace plugin\property\app\controller;

use Illuminate\Contracts\Auth\Authenticatable;
use plugin\property\app\model\PropertyUser;
use plugin\property\app\Property;
use plugin\property\app\service\PropertyUserService;
use support\Request;
use support\Response;
use Webman\Event\Event;
use yzh52521\hash\Hash;

class AuthController extends \plugin\owladmin\app\controller\AuthController
{

    protected string $serviceName = PropertyUserService::class;

    public function user(): PropertyUser|Authenticatable|null
    {
        return Property::user();
    }

    public function login(Request $request)
    {
        if (Property::config('property.auth.login_captcha')) {
            if (!$request->post('captcha')) {
                return $this->response()
                    ->fail(admin_trans('admin.required', ['attribute' => admin_trans('admin.captcha')]));
            }
            if (strtolower(cache()->pull($request->post('sys_captcha'))) != strtolower($request->post('captcha'))) {
                return $this->response()->fail(admin_trans('admin.captcha_error'));
            }
        }

        try {
            $validator = validate([
                'username' => 'require',
                'password' => 'require',
            ], [
                'username.require' => admin_trans('admin.required', ['attribute' => admin_trans('admin.username')]),
                'password.require' => admin_trans('admin.required', ['attribute' => admin_trans('admin.password')]),
            ]);
            if (!$validator->check($request->all())) {
                abort(400, $validator->getError());
            }

            $user = PropertyUser::query()->where('username', $request->post('username'))->first();

            if ($user && Hash::check($request->post('password'), $user->password)) {
                if (!$user->enabled) {
                    // 登录事件
                    Event::emit('property.login', ['username' => $user->name, 'status' => 3, 'message' => '用户未启用']);
                    return $this->response()->fail(admin_trans('admin.user_disabled'));
                }

                // $module = Admin::currentModule(true); // webman
                // $prefix = $module ? $module . '.' : ''; // webman
                $token = $this->guard()->login($user)->access_token;

                // 登录事件
                Event::emit('property.login', ['username' => $user->name, 'status' => 1, 'message' => '登陆成功']);
                return $this->response()->success(compact('token'), admin_trans('admin.login_successful'));
            }

            // 登录事件
            Event::emit('property.login', ['username' => $user->name, 'status' => 2, 'message' => '登陆失败']);
            abort(400, admin_trans('admin.login_failed'));
        } catch (\Exception $e) {
            return $this->response()->fail($e->getMessage());
        }
    }


    protected function guard()
    {
        return Property::guard();
    }

    public function currentUser(): Response
    {
        $userInfo = Property::user()->only(['name', 'avatar']);
        $menus = amis()->DropdownButton()
            ->hideCaret()
            ->className('h-full w-full')
            ->trigger('hover')
            ->btnClassName('navbar-user w-full')
            ->menuClassName('min-w-0')
            ->label($userInfo['name'])
            ->set('icon', $userInfo['avatar'])
            ->buttons([
                amis()->VanillaAction()
                    ->iconClassName('pr-2')
                    ->icon('fa fa-user-gear')
                    ->label(admin_trans('admin.user_setting'))
                    ->onClick('window.location.hash = "#/user_setting"'),
                amis()->VanillaAction()
                    ->iconClassName('pr-2')
                    ->label(admin_trans('admin.logout'))
                    ->icon('fa-solid fa-right-from-bracket')
                    ->onClick('window.$owl.logout()'),
            ]);

        return $this->response()->success(array_merge($userInfo, compact('menus')));
    }
}